<?php
defined('BASEPATH') or exit('No direct script access allowed!');

class MUser extends CI_Model {
  function __construct() {
    parent::__construct();
    $this->load->database();
    $this->load->library('elfSecurity');
  }

  function auth($username, $pwd) {
    $record = $this->db->where('username', $username)->get('user')->row();
    if(!$record) {
      return false;
    }
    if($this->elfsecurity->checkPwd($pwd, $record->password)) {
      // passed
      return $record;
    }
    return false;
  }

  function get($username) {
    $result = $this->db->select(explode(', ', 'id, username, name'))
                       ->where('username', $username)
                       ->get('user')->row();
    return $result;
  }

  function getById($id) {
    $result = $this->db->select(explode(', ', 'id, username, name'))
                       ->where('id', $id)
                       ->get('user')->row();
    return $result;
  }

  function add($username, $password, $name, $group) {
    $record = $this->get($username);
    if(!empty($record)) {
      return false;
    }
    $this->db->insert('user', array(
        'username' => $username,
        'password' => $this->elfsecurity->pwdHash($password),
        'name' => $name,
        'group' => $group
      ));
    return $this->get($username);
  }
}
